using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Pixysoft.Framework.Noebe;
using Pixysoft.Framework.Noebe.Command;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using Pixysoft.Framework.XSchEmA.Entity;

namespace Pixysoft.Framework.Noebe.Utility
{
    class IOProcessor
    {
        string basicPath = null;

        const string PATTERN_SCHEMA = "Noebe.Schema.*";

        public IOProcessor()
            : this(AppDomain.CurrentDomain.BaseDirectory)
        {
        }

        public IOProcessor(string basicpath)
        {
            basicPath = basicpath;
        }


        private DatabaseSchema ReadSchema()
        {
            string filename = basicPath + @"\" + PATTERN_SCHEMA.Replace("*", "config");

            if (!File.Exists(filename))
                return null;

            try
            {
                return Pixysoft.IO.XmlImporter.Instance.XmlImport<DatabaseSchema>(filename);
            }
            catch
            {
                return null;
            }
        }

        [ExceptionReturn(null)]
        public DatabaseSchema ReadSchema(string id)
        {
            if (string.IsNullOrEmpty(id))
                return ReadSchema();

            string filename = basicPath + @"\" + id + "." + PATTERN_SCHEMA.Replace("*", "config");

            if (!File.Exists(filename))
                return null;

            try
            {
                return Pixysoft.IO.XmlImporter.Instance.XmlImport<DatabaseSchema>(filename);
            }
            catch
            {
                return null;
            }
        }


        private void WriteSchema(DatabaseSchema database)
        {
            Pixysoft.IO.XmlExporter.Instance.XmlExport(basicPath + @"\" + "Noebe.Schema.config", database);

        }

        public void WriteSchema(string id, DatabaseSchema database)
        {
            if (string.IsNullOrEmpty(id))
            {
                WriteSchema(database);

                return;
            }

            Pixysoft.IO.XmlExporter.Instance.XmlExport(basicPath + @"\" + id + "." + "Noebe.Schema.config", database);

        }



        private void DeleteSchema()
        {
            try
            {
                File.Delete(basicPath + @"\" + "Noebe.Schema.config");
            }
            catch
            {
            }
        }

        public void DeleteSchema(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                DeleteSchema();

                return;
            }

            try
            {
                File.Delete(basicPath + @"\" + id + "." + "Noebe.Schema.config");
            }
            catch
            {
            }
        }

    }
}
